package com.nativetalk.service.three.reserve.time.insert;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.TdNtReserveTime;
import com.nativetalk.bean.reserve.ScheduleList;
import com.nativetalk.bean.reserve.TdNtReserveTimeDetail;
import com.nativetalk.bean.reserve.TdNtReserveTimeList;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.GetTeacherUtil;
import com.nativetalk.dao.TdNtReserveTimeDao;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by lizhun on 16/6/15.
 */
@Service
public class ThreeReserveTimeInsertServiceImpl implements ThreeReserveTimeInsertService {
    private static Logger logger = Logger.getLogger(ThreeReserveTimeInsertServiceImpl.class);

    /**
     * 老师可以安排时间的天数（老师可以安排14天以内的日程）
     */
    public static final int reserve_limit_days = 14;

    @Resource
    private TdNtReserveTimeDao tdNtReserveTimeDao;

    @Override
    public RetInfo setReserveTime(int tea_id, int week, int is_valid, int reserve_time) {
        String logInfo = this.getClass().getName() + ":setReserveTime:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, Integer> params = new HashMap<>();
            params.put("tea_id", tea_id);
            params.put("week", week);
            params.put("reserve_time", reserve_time);
            TdNtReserveTimeDetail detail = tdNtReserveTimeDao.findTdNtReserveTimeDetail(params);
            if (detail != null) {
                detail.setIs_valid(is_valid);
                tdNtReserveTimeDao.updateTdNtReserveTimeDetail(detail);
            } else {
                detail = new TdNtReserveTimeDetail();
                detail.setIs_valid(is_valid);
                detail.setReserve_time(reserve_time);
                detail.setReserve_week(week);
                detail.setTea_id(tea_id);
                tdNtReserveTimeDao.insertTdNtReserveTimeDetail(detail);
            }
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("修改成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    /**
     * @param detail
     * @return
     * @Purpose 修改老师的预约时间
     * @version 4.1
     * @author Peter
     */
    @Override
    @Transactional
    public RetInfo updateTdNtReserveTimeSetIsValid(TdNtReserveTimeDetail detail, TimeZone clientTimeZone) {
        String logInfo = this.getClass().getName() + ":updateTdNtReserveTimeSetIsValid:";
        Date date1 = new Date(System.currentTimeMillis());
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Integer type = detail.getType();
       /*     Date date2 = new Date(System.currentTimeMillis());
            long n1 = CommonUtil.distanceDays(date2,detail.getDate());
            if (n1 > 6){
                detail.setCurrentDate( new Date(date2.getTime() + 1000 * 60 * 60 * 24 * 7));
            }else if(n1 <= 6){
                detail.setCurrentDate(date2);
            }*/
            if (type == null) {
                retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
                retInfo.setTip(ValidationMessages.getValue("type参数错误：" + type));
            } else if (type.intValue() == 1) { //Day
                List<TdNtReserveTime> list = tdNtReserveTimeDao.findTdNtReserveByDateAndTea_id(detail);
                if (list == null || list.size() == 0) {
                    tdNtReserveTimeDao.insert(detail);
                } else {
                    tdNtReserveTimeDao.updateTdNtReserveTimeSetIsValid(detail);
                }
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("修改成功");
            } else if (type.intValue() == 2) {//Every day
                Date endDate = CommonUtil.addData(detail.getDate(), reserve_limit_days - 1);
                detail.setEndDate(endDate);
                // 先删除两周的数据
                tdNtReserveTimeDao.deleteTdNtReserveTimeSetIsValidForEveryDay(detail);
                // 然后重新插入两周的数据
                List<TdNtReserveTimeDetail> detailList = new ArrayList<>();
                for (int i = 0; i < reserve_limit_days; i++) {
                    TdNtReserveTimeDetail newDetail = new TdNtReserveTimeDetail();
                    Date date = new Date(detail.getDate().getTime() + 1000 * 60 * 60 * 24 * i);
                    newDetail.setTea_id(detail.getTea_id());
                    newDetail.setDate(date);
                    newDetail.setIs_valid(detail.getIs_valid());
                    detailList.add(newDetail);
                }
                tdNtReserveTimeDao.insertList(detailList);

                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("修改成功");
            } else if (type.intValue() == 3) {//Weekly 每周的这一天
                long n = CommonUtil.distanceDays(date1,detail.getDate());
                if (n <= 6) {
                    //修改下一周的（day-of-week）日期
                    Date endDate = CommonUtil.addData(detail.getDate(), 7);
                    detail.setEndDate(endDate);
                } else {
                    //修改上一周的（day-of-week）日期
                    Date endDate = CommonUtil.addData(detail.getDate(), -7);
                    detail.setEndDate(endDate);
                }
                //先删除这两天的数据
                tdNtReserveTimeDao.deleteTdNtReserveTimeSetIsValidForWeekly(detail);
                TdNtReserveTimeDetail newDetail_1 = new TdNtReserveTimeDetail();
                newDetail_1.setDate(detail.getDate());
                newDetail_1.setTea_id(detail.getTea_id());
                newDetail_1.setIs_valid(detail.getIs_valid());

                TdNtReserveTimeDetail newDetail_2 = new TdNtReserveTimeDetail();
                newDetail_2.setDate(detail.getEndDate());
                newDetail_2.setTea_id(detail.getTea_id());
                newDetail_2.setIs_valid(detail.getIs_valid());

                //添加这两天的数据
                tdNtReserveTimeDao.insert(newDetail_1);
                tdNtReserveTimeDao.insert(newDetail_2);

                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("修改成功");
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
                retInfo.setTip(ValidationMessages.getValue("type参数错误：" + type));
            }

            // 在更新老师日历的时候，会将原本booked的数据给更新为open状态，因此需要更新回来，更新的原理：只要有预约记录的肯定是booked状态
            tdNtReserveTimeDao.prepareBooked(detail.getTea_id());


            // 2. 查询数据
            Map<String, Object> params = new HashMap<>();
            params.put("tea_id", detail.getTea_id());
            List<ScheduleList> scheduleLists = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            long n1 = CommonUtil.distanceDays(date1, detail.getDate());
            if (n1>6){
                detail.setCurrentDate(new Date(date1.getTime() + 1000 * 60 * 60 * 24 * 7));
            }else if(n1 <= 6){
                detail.setCurrentDate(date1);
            }


            params.put("startDate", detail.getCurrentDate());
            List<TdNtReserveTimeList> tdNtReserveTimeLists = tdNtReserveTimeDao.findTdNtReserveTime(params);
            Map<Date,Integer> stringIntegerMap = new HashMap<>();
            for(TdNtReserveTimeList tdNtReserveTimeList : tdNtReserveTimeLists){
                stringIntegerMap.put(tdNtReserveTimeList.getDate(),tdNtReserveTimeList.getIs_valid());
            }

            for(int i = 0; i < 7; i++){
                ScheduleList scheduleList = new ScheduleList();
                Date startDate = new Date(detail.getCurrentDate().getTime() + 1000 * 60 * 60 * 24 * i );
                params.put("startDate", startDate);
                List<TdNtReserveTimeList> tdNtReserveTimes = GetTeacherUtil.getReserveTime(startDate,clientTimeZone);
                for(TdNtReserveTimeList tdNtReserveTimeList1 : tdNtReserveTimes){
                    if(stringIntegerMap.get(tdNtReserveTimeList1.getDate()) != null){
                        tdNtReserveTimeList1.setIs_valid(stringIntegerMap.get(tdNtReserveTimeList1.getDate()));
                    }
                }

                scheduleList.setSchedule_date(startDate);
                scheduleList.setSchedule_list(tdNtReserveTimes);
                scheduleLists.add(scheduleList);
            }
            map.put("reservetime", scheduleLists);
            retInfo.setObj(map);

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    //将时间转换成客户端的时区
    private void changeToClientTimeZone(TdNtReserveTimeList rt, TimeZone ctz) {

        //上海时区的时间
        Calendar lc = Calendar.getInstance();
        lc.set(Calendar.HOUR_OF_DAY, 0);
        lc.setTime(rt.getDate());
        rt.setDate(lc.getTime());

        //客户端时区的时间
        Calendar cc = Calendar.getInstance();
        cc.setTime(rt.getDate());
        cc.setTimeZone(ctz);
        rt.setDate(cc.getTime());//从日历中获取客户端的日期，然后设置到date
    }

    private static void print(TdNtReserveTimeList rt, Calendar lc) {
        int year = lc.get(Calendar.YEAR);
        int month = lc.get(Calendar.MONTH) + 1;
        int day = lc.get(Calendar.DAY_OF_MONTH);
        int h = lc.get(Calendar.HOUR_OF_DAY);
        int m = lc.get(Calendar.MINUTE);
        int s = lc.get(Calendar.SECOND);
        String str = "";
        if ("Asia/Shanghai".equals(lc.getTimeZone().getID())) {
            str = "[" + lc.getTimeZone().getID() + "     " + year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s + "] [" + rt.getIs_valid() + ", " + ", " + rt.getDate().getTime() + "] ";
        } else {
            str = "[" + lc.getTimeZone().getID() + "  " + year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s + "] [" + rt.getIs_valid() + ", " + ", " + rt.getDate().getTime() + "] ";
        }
        logger.info(str);

    }

    //设置给定日期的小时为hour
    private Date procHour(Date date, int hour) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        return c.getTime();
    }

}
